// #ifdef MP
var COS = require('./cos/cos');
// #endif
// #ifdef H5
var COS = require('./cos/h5cos')
// #endif
import store from '@/store/index.js'
import {config} from '@/common/config.js'
import md5Libs from "uview-ui/libs/function/md5";

function getCosToken(type) {
	return new Promise(function(resolve, reject) {
		uni.request({
			url: config.baseUrl + '/api/auth/cos?type=' + type, // 步骤二提供的签名接口
			header: {
				'Token': store.getters.Token
			},
			data: {
				bucket: config.cos.Bucket,
				region: config.cos.Region,
			},
			success: function(result) {
				var data = result.data.data;
				resolve(data)
			},
			fail: function(res) {
				reject(res)
			}
		})
	})
};

function param(key, file, backfun) {
	return {
		Bucket: config.cos.Bucket, // Bucket 格式：test-1250000000
		Region: config.cos.Region,
		Key: key,
		/* 必须 */
		FilePath: file,
		Body: file,
		onTaskReady: function(tid) {
			uni.showLoading({
				title: '准备上传'
			});
		},
		onTaskStart: function(info) {
			uni.showLoading({
				title: '开始上传'
			});
		},
		onProgress: function(progressData) {
			backfun(progressData)
		}
	}
}

function back(err, data,key, resback,errorback) {
	uni.hideLoading()
	if (err != null) {
		errorback(err.error)
		uni.showToast({
			title: "上传失败" ,
			icon: "none",
			mask:true,
		})
	} else {
		data.Location = key
		resback(data)
	}
}

function putObject(file, type, filename, backfun, resback,errorback) {
	getCosToken(type).then(function(data) {
		var credentials = data.Credentials
		var cos = new COS({
			getAuthorization: function(options, callback) {
				callback({
					TmpSecretId: credentials.TmpSecretId,
					TmpSecretKey: credentials.TmpSecretKey,
					XCosSecurityToken: credentials.Token,
					StartTime: data.StartTime,
					ExpiredTime: data.ExpiredTime,
				})
			}
		});
		let key = type + "/" + filename
		// #ifdef MP
		cos.postObject(param(key, file, backfun), function(err, data) {
			back(err, data,key, resback,errorback)
		});
		// #endif
		// #ifdef H5
		//h5 使用file 对象
		cos.putObject(param(key, file, backfun), function(err, data) {
			back(err,data, key, resback,errorback)
		});
		// #endif
	}).catch(err=>{
		errorback(err.error)
	})
}

export function upload(file, key, type, speedback, resback,errorback) {
	putObject(file, key, type, speedback, resback,errorback)
}


export function fileName(name) {
	var d = new Date().getTime();
	var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
		var r = (d + Math.random() * 16) % 16 | 0;
		d = Math.floor(d / 16);
		return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
	});
	let names = name.split('.')
	names = names[names.length-1]
	return uuid+"."+names;
}


export function fileList(lists,overupload){
	var files = [];
	lists.forEach(res=>{
		if(overupload.indexOf(res.url)===-1)
			files.push(res)
	})
	return files
}

export function fileIndex(lists,url){
	for(let i in lists){
		if(lists[i].url===url){
			return i 
		}
	}
}

export function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}

export function fileSuffix(type){
	switch(type){
		case "image":return ['png', 'jpg', 'jpeg', 'webp', 'gif']
		case "vido":return ["avi","mov","rmvb","flv","mp4"]
		case "music":return ["mp3","wav","aif","au","ra","rm","ram","mid","rmi"]
		case "document":return ["txt","pdf","pdfx","xlsx","xls","doc","docx","ppt","pptx"]
		case "compress":return ["rar","zip","gz","z","7z"]
		default:return ['png', 'jpg', 'jpeg', 'webp', 'gif',"avi","mov","rmvb","flv","mp4"]
	}
}